package com.zkingsoft.rhi.interceptor;

import com.alibaba.fastjson.JSONObject;
import com.zkingsoft.rhi.handler.Result;
import com.zkingsoft.rhi.jwt.Jwt;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author xieguo
 * @since 2020/11/4 14:08
 */

public class LoginHandlerInterceptor implements HandlerInterceptor {

    @Value("${my.debug}")
    private String debug;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        if ("true".equals(debug)){
            return true;
        }

//        System.out.println("================进入拦截器======================");

        String token = request.getHeader("token");

        if (null==token||Jwt.parseJwt(token).isEmpty()){
            JSONObject jsonObject = Result.setResultByCodeAndMsg(Result.VALIDATION_FAILED, "未登录，或者登录超时");
            String s = jsonObject.toJSONString();
            response.setCharacterEncoding("utf-8");
            response.setContentType("text/html;charset=UTF-8");
            response.getOutputStream().write(s.getBytes());
            return false;
        }else {
            return true;
        }


    }
}
